﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Net.Http;
using System.Net.Http.Headers;

namespace Dapper.SimpleDao.Test
{
    public class ApiHelper
    {
        private ApiHelper() { }
        public static readonly ApiHelper Instance = new ApiHelper();

        private static readonly string ClientId = "defalut";
        private static readonly string ClientSercet = "defalut";
        private static readonly string API = "http://localhost:42507/";


       
        public string GetClientToken()
        {
            using (var client = new HttpClient())
            {
                List<KeyValuePair<string, string>> paramList = new List<KeyValuePair<string, string>>();
                paramList.Add(new KeyValuePair<string, string>("client_id", ClientId));
                paramList.Add(new KeyValuePair<string, string>("client_sercet", ClientSercet));
                paramList.Add(new KeyValuePair<string, string>("grant_type", "client_credentials"));
                var content = new FormUrlEncodedContent(paramList);
                var response = client.PostAsync(API + "oauth2/token", content).Result;
                var result = response.Content.ReadAsStringAsync().Result;
                return result;
            }
        }

        public string GetUserToken()
        {
            using (var client = new HttpClient())
            {
                List<KeyValuePair<string, string>> paramList = new List<KeyValuePair<string, string>>();
                paramList.Add(new KeyValuePair<string, string>("client_id", ClientId));
                paramList.Add(new KeyValuePair<string, string>("username", "aa"));
                paramList.Add(new KeyValuePair<string, string>("password", "bb"));
                paramList.Add(new KeyValuePair<string, string>("grant_type", "password"));
                var content = new FormUrlEncodedContent(paramList);
                var response = client.PostAsync(API + "oauth2/token", content).Result;
                var result = response.Content.ReadAsStringAsync().Result;
                return result;
            }
        }



        public string PostJsonResponse(string url, string token, string json)
        {
            using (var client = new HttpClient())
            {
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
                var content = new StringContent(json);
                content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                var response = client.PostAsync(API + url, content).Result.Content.ReadAsStringAsync().Result;
                return response;
            }

        }


    }
}